package com.sdhs.projectschedule.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import com.sdhs.businessfile.domain.BusinessFile;
import com.sdhs.businessfile.service.IBusinessFileService;
import com.sdhs.common.core.domain.event.ProcessEvent;
import com.sdhs.common.enums.BusinessStatusEnum;
import com.sdhs.common.enums.BusinessTypeEnum;
import com.sdhs.common.utils.*;
import com.sdhs.myproject.domain.GcMyprojectInformation;
import com.sdhs.myproject.service.IGcMyprojectInformationService;
import com.sdhs.projectschedule.domain.GcProgressHandIn;
import com.sdhs.projectschedule.domain.GcProgressProjectEnd;
import com.sdhs.projectschedule.mapper.GcProgressProjectEndMapper;
import com.sdhs.projectschedule.service.IGcProgressProjectEndService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 项目进度控制--项目结束Service业务层处理
 *
 * @author andong
 * @date 2025-04-29
 */
@Service
public class GcProgressProjectEndServiceImpl implements IGcProgressProjectEndService {
    @Autowired
    private GcProgressProjectEndMapper gcProgressProjectEndMapper;

    @Autowired
    private IBusinessFileService businessFileService;

    @Autowired
    private IGcMyprojectInformationService gcInformationService;
    /**
     * 查询项目进度控制--项目结束
     *
     * @param id 项目进度控制--项目结束主键
     * @return 项目进度控制--项目结束
     */
    @Override
    public GcProgressProjectEnd selectGcProgressProjectEndById(Long id) {
        GcProgressProjectEnd gcProgressProjectEnd = gcProgressProjectEndMapper.selectGcProgressProjectEndById(id);
        List<BusinessFile> businessFiles = businessFileService.listByBusinessTypeAndId(BusinessTypeEnum.GC_PROGRESS_PROJECT_END.getCode(), String.valueOf(id));
        gcProgressProjectEnd.setFileList(businessFiles);
        return gcProgressProjectEnd;
    }

    /**
     * 查询项目进度控制--项目结束列表
     *
     * @param gcProgressProjectEnd 项目进度控制--项目结束
     * @return 项目进度控制--项目结束
     */
    @Override
    public List<GcProgressProjectEnd> selectGcProgressProjectEndList(GcProgressProjectEnd gcProgressProjectEnd) {
        return gcProgressProjectEndMapper.selectGcProgressProjectEndList(gcProgressProjectEnd);
    }

    /**
     * 新增项目进度控制--项目结束
     *
     * @param gcProgressProjectEnd 项目进度控制--项目结束
     * @return 结果
     */
    @Override
    public GcProgressProjectEnd insertGcProgressProjectEnd(GcProgressProjectEnd gcProgressProjectEnd) {
        gcProgressProjectEnd.setCreater(SecurityUtils.getUsername());
        gcProgressProjectEnd.setCreateTime(DateUtils.getNowDate());
        gcProgressProjectEnd.setApprovalStatus(BusinessStatusEnum.DRAFT.getStatusValue());
        gcProgressProjectEndMapper.insertGcProgressProjectEnd(gcProgressProjectEnd);
        handler(gcProgressProjectEnd.getId(), gcProgressProjectEnd);
        return gcProgressProjectEnd;
    }

    /**
     * 修改项目进度控制--项目结束
     *
     * @param gcProgressProjectEnd 项目进度控制--项目结束
     * @return 结果
     */
    @Override
    public int updateGcProgressProjectEnd(GcProgressProjectEnd gcProgressProjectEnd) {
        gcProgressProjectEnd.setUpdater(SecurityUtils.getUsername());
        gcProgressProjectEnd.setUpdateTime(DateUtils.getNowDate());
        int i = gcProgressProjectEndMapper.updateGcProgressProjectEnd(gcProgressProjectEnd);
        handler(gcProgressProjectEnd.getId(), gcProgressProjectEnd);
        return i;
    }

    /**
     * 批量删除项目进度控制--项目结束
     *
     * @param ids 需要删除的项目进度控制--项目结束主键
     * @return 结果
     */
    @Override
    public int deleteGcProgressProjectEndByIds(Long[] ids) {
        return gcProgressProjectEndMapper.deleteGcProgressProjectEndByIds(ids);
    }

    /**
     * 删除项目进度控制--项目结束信息
     *
     * @param id 项目进度控制--项目结束主键
     * @return 结果
     */
    @Override
    public int deleteGcProgressProjectEndById(Long id) {
        GcProgressProjectEnd gcProgressProjectEnd = gcProgressProjectEndMapper.selectGcProgressProjectEndById(id);
        gcProgressProjectEnd.setIsDelete("1");
        return gcProgressProjectEndMapper.updateGcProgressProjectEnd(gcProgressProjectEnd);
    }

    /*项目结束审批监听*/
    @org.springframework.context.event.EventListener(condition = "#processEvent.key.startsWith('progress_project_end')")
    public void processHandler(ProcessEvent processEvent) {

        // 已完成（已通过）
        if (BusinessStatusEnum.FINISH.getStatus().equals(processEvent.getStatus())) {
            String businessKey = processEvent.getBusinessKey();
             GcProgressProjectEnd gcProgressProjectEnd = gcProgressProjectEndMapper.selectGcProgressProjectEndByInstanceId(businessKey);

            GcMyprojectInformation gcMyprojectInformation = new GcMyprojectInformation();
            gcMyprojectInformation.setId(gcProgressProjectEnd.getProjectId());
            gcMyprojectInformation.setProjectStatus("5");
            gcMyprojectInformation.setEndTime(gcProgressProjectEnd.getEndTime());
            /*修改项目状态为已完成*/
            gcInformationService.updateGcMyProject(gcMyprojectInformation);
            /*获取项目交工信息中是否有商机id，如果有商机id的话，将信息推送到营销项目中*/
            if (gcProgressProjectEnd.getBusinessId()!=null){
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("businessId", gcProgressProjectEnd.getBusinessId());
                jsonObject.addProperty("statusId", "4");
                jsonObject.addProperty("isOrganization", gcProgressProjectEnd.getIsOrganization());
                try {
                    String jsonData = jsonObject.toString(); // 直接转为JSON字符串
                    String encryptedData = AESUtils.encrypt(jsonData);
                    /*推送营销接口*/
                    PushUtil.pushUrl(encryptedData);
                } catch (JsonProcessingException e) {
                    System.err.println("JSON序列化失败: " + e.getMessage());
                    throw new RuntimeException(e);
                } catch (Exception e) {
                    System.err.println("加密失败: " + e.getMessage());
                    throw new RuntimeException(e);
                }
            }

            /*推送安全项目开始*/
            if (gcProgressProjectEnd.getProjectId()!=null){
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("engineeringId", gcProgressProjectEnd.getProjectId()); //项目id
                jsonObject.addProperty("type", "update"); //类型
                jsonObject.addProperty("status", "5"); //项目状态-已完成
                try {
                    String jsonData = jsonObject.toString(); // 直接转为JSON字符串
                    String encryptedData = AESUtils.encrypt(jsonData);
                    /*推送安全接口*/
                    SafetyUtil.pushUrl(encryptedData);
                } catch (JsonProcessingException e) {
                    System.err.println("JSON序列化失败: " + e.getMessage());
                    throw new RuntimeException(e);
                } catch (Exception e) {
                    System.err.println("加密失败: " + e.getMessage());
                    throw new RuntimeException(e);
                }
            }
            /*推送安全项目结束*/
        }

    }
    /**
     * 保存联合数据
     * 保存合同附件
     */
    public void handler(Long id, GcProgressProjectEnd gcProgressProjectEnd) {
        // 保存合同附件
        businessFileService.saveFileBatch(BusinessTypeEnum.GC_PROGRESS_PROJECT_END.getCode(), String.valueOf(id), gcProgressProjectEnd.getFileList());
    }
}
